package org.mspring.mlog.dao.impl;

import java.util.List;

import org.mspring.mlog.dao.TreeItemDao;
import org.mspring.mlog.entity.TreeItem;
import org.mspring.mlog.entity.em.TreeItemType;
import org.mspring.nbee.orm.dao.impl.BaseDao;
import org.mspring.nbee.orm.dao.sql.Sql;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Gao Youbo
 * @since 2014-09-10 11:51:15
 */
@Repository
public class TreeItemDaoImpl extends BaseDao<TreeItem> implements TreeItemDao {

    @Override
    public List<TreeItem> listByRole(long roleId) {
        Sql sql = new Sql("select ti.* from t_tree_item ti left join t_role_tree_item rti on ti.id = rti.tree_item_id where rti.role_id = ?", roleId);
        return super.listBySql(sql);
    }

    @Override
    public List<TreeItem> listTreeByUser(long userId) {
        Sql sql = new Sql(
                "select tree_item.* from t_tree_item tree_item left join t_role_tree_item role_tree_item on role_tree_item.tree_item_id = tree_item.id left join t_user_role user_role on user_role.role_id = role_tree_item.role_id where tree_item.deleted = false and user_role.user_id = ? and tree_item.type in (?, ?) order by tree_item.id",
                userId, TreeItemType.TREE_FOLDER, TreeItemType.TREE_ITEM);
        return super.listBySql(sql);
    }

    @Override
    public List<TreeItem> listTabByUser(String parent, long userId) {
        Sql sql = new Sql(
                "select tree_item.* from t_tree_item tree_item left join t_role_tree_item role_tree_item on role_tree_item.tree_item_id = tree_item.id left join t_user_role user_role on user_role.role_id = role_tree_item.role_id where tree_item.deleted = false and tree_item.parent = ? and user_role.user_id = ? and tree_item.type = ? order by tree_item.id",
                parent, userId, TreeItemType.TAB);
        return super.listBySql(sql);
    }

    @Override
    public TreeItem getOpenTab(String parent, long userId) {
        Sql sql = new Sql(
                "select tree_item.* from t_tree_item tree_item left join t_role_tree_item role_tree_item on role_tree_item.tree_item_id = tree_item.id left join t_user_role user_role on user_role.role_id = role_tree_item.role_id where tree_item.deleted = false and tree_item.parent = ? and user_role.user_id = ? and tree_item.type = ? and tree_item.open = true order by tree_item.id",
                parent, userId, TreeItemType.TAB);
        return super.findBySql(sql);
    }

}
